<?php


namespace app\admin\controller\hospital;


use app\common\controller\Adminbase;
use think\Db;

class Hospital extends Adminbase
{
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit) = $this->buildTableParames();
            //获取列表
            $business_where[] = ['is_del', '=', 0];
            $filter = input('filter');
            if ($filter) {
                $filter = json_decode($filter, true);
                if (isset($filter['id'])) {
                    $business_where[] = ['id', '=', $filter['id']];
                }
                if (isset($filter['c_address'])) {
                    $business_where[] = ['address', 'like', '%' . $filter['c_address'] . '%'];
                }
                if (isset($filter['province'])) {
                    $province = Db::name('area')->find($filter['province']);
                    $business_where[] = ['province', '=', $province['name']];
                }
                if (isset($filter['city'])) {
                    $city = Db::name('area')->find($filter['city']);
                    $business_where[] = ['city', '=', $city['name']];
                }
                if (isset($filter['create_time'])) {
                    $create_time = explode(' - ', $filter['create_time']);
                    foreach ($create_time as $k => $v) {
                        $create_time[$k] = strtotime($v);
                    }
                    $business_where[] = ['create_time', 'between', [$create_time[0], $create_time[1]]];
                }
            }
            $_list = Db::name('hospital')
                ->page($page, $limit)
                ->where($business_where)
                ->order('sort desc')
                ->order('create_time desc')
                ->select();
            foreach ($_list as $k => $v) {
                $_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $_list[$k]['c_address'] = $v['province'] . $v['city'] . $v['area'] . $v['address'];
                $_list[$k]['department_num'] = Db::name('department')
                    ->where(['is_del'=>0,'hospital_id'=>$v['id'],'pid'=>0])
                    ->count();
            }
            //获取数量
            $total = Db::name('hospital')
                ->where($business_where)
                ->count();
            $result = ["code" => 0, "count" => $total, "data" => $_list];
            return json($result);
        }
        $area_list = Db::name('area')->where([
            ['id', '<>', 0],
            ['pid', '=', 0]
        ])->select();
        foreach ($area_list as $k => $v) {
            $proviec[$v['id']] = $v['name'];
        }
        $this->assign('proviec', $proviec);
        return $this->fetch();
    }

    //增加
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['row']['create_time'] = time();

            $address = getLWByAddress($data['row']['province'] . $data['row']['city'] . $data['row']['area'] . $data['row']['address']);
            $address = json_decode($address, true);
            if ($address['code'] == 0) {
                $data['row']['longitude'] = $address['data'][0];
                $data['row']['latitude'] = $address['data'][1];
            } else {
                $this->error('输入正确位置');
            }
            //真实城市
            $city_array = array('北京市', '上海市', '天津市', '重庆市');
            if (in_array($data['row']['province'], $city_array)){
                $data['row']['real_city']=$data['row']['province'];
            }else{
                $data['row']['real_city']=$data['row']['city'];
            }
            $stmt = Db::name('hospital')->insertGetId($data['row']);
            if ($stmt) {
                $this->success('操作成功！');
            } else {
                $this->error('操作失败！');
            }
        } else {
            $area_list = Db::name('area')->where([
                ['id', '<>', 0],
                ['pid', '=', 0]
            ])->select();
            $this->assign('proviec', $area_list);
            return $this->fetch();
        }
    }

    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $address = getLWByAddress($data['row']['province'] . $data['row']['city'] . $data['row']['area'] . $data['row']['address']);
            $address = json_decode($address, true);
            if ($address['code'] == 0) {
                $data['row']['longitude'] = $address['data'][0];
                $data['row']['latitude'] = $address['data'][1];
            } else {
                $this->error('输入正确位置');
            }

            //真实城市
            $city_array = array('北京市', '上海市', '天津市', '重庆市');
            if (in_array($data['row']['province'], $city_array)){
                $data['row']['real_city']=$data['row']['province'];
            }else{
                $data['row']['real_city']=$data['row']['city'];
            }

            $data = Db::name('hospital')
                ->where('id', $data['id'])
                ->update($data['row']);
            $this->success('操作成功');
        }
        $data = Db::name('hospital')->find($id);
        $proviec_list = Db::name('area')->where([
            ['id', '<>', 0],
            ['pid', '=', 0]
        ])->select();
        $provice = Db::name('area')->where(['name' => $data['province']])->find();
        $city_list = Db::name('area')->where([
            'pid' => $provice['id']
        ])->select();
        $city = Db::name('area')->where(['name' => $data['city']])->find();
        $area_list = Db::name('area')->where([
            'pid' => $city['id']
        ])->select();
        if ($area_list[0]['name'] == "市辖区") {
            $area_list2 = Db::name('area')->where([
                'pid' => $area_list[0]['id']
            ])->select();
            foreach ($area_list2 as $k => $v) {
                $area_list[] = $v;
            }
            unset($area_list[0]);
        }
        usort($area_list, function ($a, $b) {
            return $a['id'] - $b['id'];
        });
        $this->assign([
            'data' => $data,
            'city_list' => $city_list,
            'proviec' => $proviec_list,
            'area_list' => $area_list
        ]);
        return $this->fetch();
    }

    //删除
    public function del()
    {
        $ids = $this->request->param('ids/a', null);
        try {
            foreach ($ids as $id) {
                Db::name('hospital')->where('id', $id)->update([
                    'is_del' => 1,
                ]);
            }
        } catch (\Exception $ex) {
            $this->error($ex->getMessage());
        }
        $this->success('删除成功！');
    }

    public function getc_cate()
    {
        $id = input('id');
        $detail = Db::name('area')->where('name', $id)->find();
        $query = db('area')->where('pid', $detail['id'])->select();

        if ($query[0]['name'] == "市辖区") {
            $area_list2 = Db::name('area')->where([
                'pid' => $query[0]['id']
            ])->select();
            foreach ($area_list2 as $k => $v) {
                $query[] = $v;
            }
            unset($query[0]);
        }
        usort($query, function ($a, $b) {
            return $a['id'] - $b['id'];
        });

        return json(['code' => 200, 'data' => $query, 'msg' => '获取成功']);
    }

    public function getc_cate2()
    {
        $id = input('id');
        $query = db('area')->where('pid', $id)->select();
        return json(['code' => 200, 'data' => $query, 'msg' => '获取成功']);
    }


    /**
     * 状态
     */
    public function setstate()
    {
        $id = $this->request->param('id/d', 0);

        $status = $this->request->param('value/d');

        if (Db::name('hospital')->where('id', $id)->update(['status' => $status])) {

            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //设置
    public function DepartmentList()
    {
        $id = $this->request->param('id/d', 0);
        if ($this->request->isAjax()) {
            $_list = Db::name('department')
                ->where(['is_del' => 0, 'hospital_id' => $id])
                ->order('sort desc')
                ->select();
            $_list2=listToTree($_list);
            $_list3=array();
            foreach ($_list2 as $k=>$v){
                unset($_list2[$k]['_child']);
                $_list3[]=$_list2[$k];
                if ($v['_child']){
                    foreach ($v['_child'] as $k2=>$v2){
                        $v2['name']='├─'.$v2['name'];
                        $_list3[]=$v2;
                    }
                }
            }
            $result = ["code" => 0, "count" => '', "data" => $_list3];
            return json($result);
        }
        $this->assign([
            'hospital_id' => $id
        ]);
        return $this->fetch();
    }

    //增加
    public function DepartmentAdd()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data['row']['pid']){
                $data['row']['pid']=0;
            }
            $stmt = Db::name('department')->insertGetId($data['row']);
            if ($stmt) {
                $this->success('操作成功！');
            } else {
                $this->error('操作失败！');
            }
        }
        $id = $this->request->param('id/d', null);
        $pid = $this->request->param('pid/d', null);
        $this->assign([
            'hospital_id' => $id,
            'pid'=>$pid
        ]);
        return $this->fetch();
    }

    public function DepartmentEdit()
    {
        $id = $this->request->param('id/d', 0);
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data = Db::name('department')
                ->where('id', $data['row']['id'])
                ->update($data['row']);
            $this->success('操作成功');
        }
        $data = Db::name('department')->find($id);
        $this->assign([
            'data' => $data,
        ]);
        return $this->fetch();
    }

    //删除
    public function DepartmentDel()
    {
        $ids = $this->request->param('ids/a', null);
        try {
            foreach ($ids as $id) {
                $c_ids=Db::name('department')->where('pid','=',$id)->column('id');
                $c_ids[]=$id;
                Db::name('department')->where('id','in',$c_ids)->update([
                    'is_del' => 1,
                ]);
            }
        } catch (\Exception $ex) {
            $this->error($ex->getMessage());
        }
        $this->success('删除成功！');
    }

    public function setstate2()
    {
        $id = $this->request->param('id/d', 0);

        $status = $this->request->param('value/d');

        if (Db::name('department')->where('id', $id)->update(['status' => $status])) {

            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

}